import { makeAutoObservable } from 'mobx'
import { organOrTeacherLoginApi, companyLoginApi, getWebsiteList } from './api'
import { Toast } from 'antd-mobile'
import { setLocalStorage } from '@/storage'
import { history } from 'umi'
import type {
    PickerColumn,
    PickerColumnItem,
    PickerValue,
} from 'antd-mobile/es/components/picker-view/picker-view'
import type { LoginFormType, TabValue } from './interface'

class Store {
    tab: TabValue = 'company'
    websiteDefault: PickerValue[] = []
    websiteName: string = ''
    websiteList: PickerColumn[] = []
    websitePickerVisible: boolean = false

    constructor() {
        makeAutoObservable(this)
        this.getWebsiteList()
    }

    /** 获取 站点列表 */
    getWebsiteList = () => {
        getWebsiteList().then(res => {
            this.websiteList = [
                (res.data || []).map(item => ({
                    label: item.name,
                    value: item.domain,
                    key: item.code,
                })),
            ]
            const item = this.websiteList[0][0] as PickerColumnItem

            this.websiteDefault = [item.value]
            this.websiteName = item.label as string

            setLocalStorage('SITE_DOMAIN', item.value)
        })
    }

    /** 切换登录角色 */
    onChangeTabs = (tab: TabValue) => {
        this.tab = tab
    }

    /** 确认选择站点 */
    onConfirmWebsitePicker = (item: PickerValue[]) => {
        const domain = item[0]

        // 接口请求时从LocalStorage读取X-Site-Domain请求头
        setLocalStorage('SITE_DOMAIN', domain)

        this.websiteDefault = [domain]
        this.websiteName = (this.websiteList[0].find(
            fItem => (fItem as PickerColumnItem).value === domain,
        ) as PickerColumnItem).label as string
        this.websitePickerVisible = false
    }

    /** 登录 */
    login = async (value: Pick<LoginFormType, 'username' | 'password'>) => {
        let loginData: any = {}
        const appid = 'wxdbb895b041d72410'

        if (this.tab === 'company') {
            const res = await companyLoginApi({
                username: value.username,
                password: value.password,
                type: 2,
                appid,
            })

            loginData = res.data
        } else {
            // appid 小程序登录接口改动，必须传相应的小程序appid，年度报告登录无法获取相应的appid，暂时传沃创课堂用户端小程序appid
            const res = await organOrTeacherLoginApi({
                username: value.username,
                password: value.password,
                role: this.tab,
                type: 1,
                appid,
            })

            loginData = res.data
        }

        if (Object.keys(loginData).length === 0) return

        setLocalStorage('LOGIN_INFO', loginData)
        setLocalStorage('ACCESS_TOKEN', loginData.access_token)

        history.push('/report/entry')
        Toast.show({
            icon: 'success',
            content: '登录成功',
        })
    }
}

export default Store
